package com.gopay.common.trace;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.gopay.common.trace.def.Span;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.Log4jLoggerAdapter;
import org.slf4j.spi.LocationAwareLogger;

/**
 * 追踪日志打印工具类
 * Created by xuHui on 2017/5/12.
 */
public enum TraceLogUtils {
    INSTANCE;

    private static final Logger logger = LoggerFactory.getLogger(TraceLogUtils.class);

    private static SimplePropertyPreFilter filter = new SimplePropertyPreFilter();

    static {
        filter.getExcludes().add("childs");
        filter.getExcludes().add("sample");
    }


    /***
     * 是否debug 输出
     * 主要用来打印 一些 调试阶段的 数据
     * ******* 上线时 将 变量改为 false
     */
    private static final boolean isDebug = true;


    /**
     * 打印调试日志
     * @param logger
     * @param format
     * @param arg
     */
    public static void debugLog(String format, Object arg, String FQCN) {
        if (isDebug) {
            logger.warn("调试日志-" + format , arg);
        }
    }

    public static void debugLog(String format, Object arg ) {
        if (isDebug) {

            logger.warn("调试日志-" + format , arg);
        }
    }

    /***
     * 打印调试日志
     * @param logger
     * @param format
     * @param argArr
     */
    public static void debugLog(Logger logger1, String format, Object[] argArr) {
        if (isDebug) {
            logger1.warn("调试日志-" + format , argArr);
        }
    }


    public static void log(TraceLog traceLog) {

        Object obj = traceLog.getMessage();
        String message = null;
        if (obj instanceof Span) {
            message = JSON.toJSONString(obj, filter);
        } else if (obj instanceof String) {
            //字符串的  就不需要在json化了
            message = (String) obj;
        } else {
            message = JSON.toJSONString(obj);
        }

        if (StringUtils.isBlank(message)) {
            return;
        }

        if (traceLog.getException() != null) {
            logger.error(traceLog.getTraceType() + " " + traceLog.getTime() + " " + message, traceLog.getException());
        } else {
            logger.info(traceLog.getTraceType() + " " + traceLog.getTime() + " " + message);
        }
    }
}
